package admin

import (
	//"net/http"
	"fmt"
	//"log"
	"encoding/base64"
	"encoding/json"
	"regexp"
	"strings"

	"github.com/gin-gonic/gin"

	"golang-admin/app/models"
)

// 定义全局变量
var (
	adminInfo models.Admin
	//adminMenus models.AdminMenu
	sidebar string
)

type ApiResponse struct {
	Code   int         `json:"code"`
	Status int         `json:"status"`
	Msg    string      `json:"msg"`
	Data   interface{} `json:"data"`
}

// 初始化
func Initialize(c *gin.Context) {
	// 读取 cookie
	sessionAdmin, admin_err := c.Cookie("ADMIN")
	if admin_err != nil {
		c.Redirect(302, "/admin/auth/login")
	}
	fmt.Printf("admin cookie : %s\n", sessionAdmin)
	stringAdmin := sessionAdmin
	// 解析成json
	jsonAdmin, _ := base64.URLEncoding.DecodeString(stringAdmin)

	err := json.Unmarshal([]byte(string(jsonAdmin)), &adminInfo)
	if err != nil {
		fmt.Println(err)
	}

	// 检查权限
	access, _ := CheckAccess(adminInfo)
	if !access {
		fmt.Fprint(c.Writer, "您没有访问权限！")
	}

	// 初始化后台菜单
	menus := models.GetTree(0, 0, 1)
	// 使用全局变量
	sidebar = sidebarHtml(c, menus)
}

// 通过 Cookie 判断用户是否已登录
func CheckAccess(adminInfo models.Admin) (valid bool, err error) {
	// TODO
	fmt.Println("CheckAccess : ", adminInfo.Username)
	valid = true
	return
}

func sidebarHtml(c *gin.Context, menus []*models.AdminMenu) (outputs string) {
	uri := c.Request.RequestURI
	if strings.Index(uri, "?") > 0 {
		uri = uri[1:strings.Index(uri, "?")]
	} else {
		uri = uri[1:]
	}
	if uri == "admin" {
		uri = "admin/dashboard/index"
	}
	//fmt.Println(uri)
	uriArr := strings.Split(uri, "/")
	if len(regexp.MustCompile("add").FindAllString(uriArr[2], -1)) > 0 || len(regexp.MustCompile("edit").FindAllString(uriArr[2], -1)) > 0 {
		uriArr[2] = "index"
	}

	var subMenu func(menus []*models.AdminMenu, level int) string
	subMenu = func(menus []*models.AdminMenu, level int) string {
		output := ""
		for _, menu := range menus {
			if level == 0 {
				icon := ""
				if menu.Parent > 0 {
					if menu.Icon != "" {
						icon = menu.Icon
					} else {
						icon = "fa fa-caret-right"
					}
				} else {
					icon = menu.Icon
				}
				active := ""
				if uriArr[0] == strings.ToLower(menu.App) && uriArr[1] == strings.ToLower(menu.Controller) && uriArr[2] == strings.ToLower(menu.Action) {
					active = "layui-this"
				}
				if len(menu.Items) == 0 {
					output += "<li class='layui-nav-item " + active + "' data-name='" + menu.Name + "'>"
					output += "<a href='" + menu.Url + "' lay-tips='" + menu.Name + "' target='" + menu.Target + "'>"
					output += "<i class='layui-icon " + icon + "'></i>"
					output += "<cite>" + menu.Name + "</cite>"
					output += "</a>"
					output += "</li>"
				} else {
					class := ""
					if uriArr[0] == strings.ToLower(menu.App) && uriArr[1] == strings.ToLower(menu.Controller) && uriArr[2] == strings.ToLower(menu.Action) {
						class = "layui-nav-itemed"
					}
					output += "<li class='layui-nav-item " + class + "' data-name='" + menu.Name + "'>"
					output += "<a href='javascript:;' lay-tips='" + menu.Name + "'>"
					output += "<i class='layui-icon " + icon + "'></i>"
					output += "<cite>" + menu.Name + "</cite>"
					output += "</a>"
					output += "<dl class='layui-nav-child'>"
					output += subMenu(menu.Items, level+1)
					output += "</dl>"
					output += "</li>"
				}
			} else {
				active := ""
				if uriArr[0] == strings.ToLower(menu.App) && uriArr[1] == strings.ToLower(menu.Controller) && uriArr[2] == strings.ToLower(menu.Action) {
					active = "layui-this"
				}
				if len(menu.Items) == 0 {
					output += "<dd class='" + active + "'>"
					output += "<a href='" + menu.Url + "' target='" + menu.Target + "'>"
					output += menu.Name
					output += "</a>"
					output += "</dd>"
				} else {
					class := ""
					if uriArr[0] == strings.ToLower(menu.App) && uriArr[1] == strings.ToLower(menu.Controller) && uriArr[2] == strings.ToLower(menu.Action) {
						class = "layui-nav-itemed"
					}
					output += "<dd class='" + class + "' data-name='" + menu.Name + "'>"
					output += "<a href='javascript:;' lay-tips='" + menu.Name + "'>"
					output += menu.Name
					output += "</a>"
					output += "<dl class='layui-nav-child'>"
					output += subMenu(menu.Items, level+1)
					output += "</dl>"
					output += "</dd>"
				}
			}
		}

		return output
	}
	outputs = subMenu(menus, 0)

	return
}
